home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9888 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: news.unt.edu!news
  2. From: Steve Fogoros <sfogoros@hsc.unt.edu>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Determining the length of an int in string form
  5. Date: Wed, 13 Mar 1996 22:34:53 -0800
  6. Organization: University of North Texas Health Science Center
  7. Message-ID: <3147BE0D.296@hsc.unt.edu>
  8. References: <3146D058.DD7@cbm.com>
  9. NNTP-Posting-Host: sfogoros.hsc.unt.edu
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (Win16; I)
  14.  
  15. Dave Payne wrote:
  16. > Consider this:
  17. > I have a variable of type int, and I would like to use the sprintf()
  18. > function to write this variable to a string.  However, I want to
  19. > dynamically allocate the space for the string, and only malloc enough
  20. > space to hold the int.  Here's a code fragment that may illustrate this
  21. > more clearly:
  22.  
  23. Here is what I would do,
  24.  
  25.  char buf[80]; // int could be any length when converted. (Twenty years from now
  26.                //    will int be 256 bits? That would be over 80 digits.)
  27.                // In the mean time you should make buf at least buf[12] because
  28.                //    int could be 32 bits. For 64 bit use buf[22];
  29.  
  30.  void func1()  {
  31.  
  32.    int    i = 1234;
  33.    char  *a;
  34.  
  35.    sprintf(buf,"%s%d","The value of i is ",i);
  36.    a = malloc(strlen(buf + 1));
  37.    if(!a) get_outta_here("malloc error");
  38.    strcpy(a,buf);
  39.    printf("%s\n",a);
  40.    free(a);
  41. }
  42.  
  43.  
  44. -- 
  45. Steve Fogoros, Academic Information Coordinator
  46. University of North Texas Health Science Center
  47. sfogoros@hsc.unt.edu
  48.